#!/bin/sh

check_header()
{
	echo "Checking for header: $1 ..."
	if echo '#include' "<$1>" | cpp $CFLAGS >/dev/null 2>&1; then
		echo '    found.'
		return 0
	else
		echo '    not found.'
		return 1
	fi
}

PREFIX='/usr/local'
debug=true
opt=false

sys=`uname -s`

# X11-options
if [ $sys != Darwin ]; then
	xrandr=true
	xf86vm=true
else
	xrandr=false
	xf86vm=false
fi

arg0=$0
while [ $# -gt 0 ]; do
	case $1 in
	--prefix=*)
		PREFIX=`echo $1 | sed 's/--prefix=//'`
		;;
	--enable-*)
		`echo $1 | sed 's/--enable-//'`=true
		;;
	--disable-*)
		`echo $1 | sed 's/--disable-//'`=false
		;;

	--help)
		echo "Usage: $arg0 [options]"
		echo "  --prefix=<path>   set installation prefix (default: /usr/local)"
		echo "  --enable-debug    enable debugging symbols (default)"
		echo "  --disable-debug   disable debugging symbols"
		echo "  --enable-opt      enable compiler optimizations"
		echo "  --disable-opt     disable compiler optimizations (default)"
		echo "  --enable-xrandr   enable mode switching with XR&R on X11 (default)"
		echo "  --disable-xrandr  disable mode switching with XR&R on X11"
		echo "  --enable-xf86vm   enable mode switching with XF86VidMode on X11 (default)"
		echo "  --disable-xf86vm  disable mode switching with XF86VidMode on X11"
		exit 0
	esac
	shift
done

if $xrandr; then
	if ! check_header X11/extensions/Xrandr.h; then
		xrandr=false
	fi
fi
if $xf86vm; then
	if ! check_header X11/extensions/xf86vmode.h; then
		xf86vm=false
	fi
fi

echo '# Generated makefile, do not edit' >Makefile
echo "PREFIX = $PREFIX" >>Makefile
if $opt; then
	echo 'opt = -O3' >>Makefile
fi
if $debug; then
	echo 'dbg = -g' >>Makefile
fi

if $xrandr; then
	echo 'CFLAGS_xrandr = -DUSE_XRANDR' >>Makefile
	echo 'LDFLAGS_xrandr = -lXrandr' >>Makefile
fi

if $xf86vm; then
	echo 'CFLAGS_xf86vm = -DUSE_XF86VM' >>Makefile
	echo 'LDFLAGS_xf86vm = -lXxf86vm' >>Makefile
fi

echo '# ----------------------------' >>Makefile
cat Makefile.in >>Makefile

echo 'done. run make (or gmake) to build'
